package com.leyou.interceptor;

import com.leyou.api.ActivityService;
import com.leyou.domain.db1entity.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PassportInterceptor implements HandlerInterceptor {


    @Autowired
    ActivityService activityService;


    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String ticket = null;
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("ticket")) {
                    ticket = cookie.getValue();
                }
                break;
            }
        }

        if (ticket == null || "".equals(ticket)) {
            response.sendRedirect("./login.html");
            return true;
        }


        if (!redisTemplate.hasKey(ticket)) {
            response.sendRedirect("./login.html");
            return true;
        }

        Manager manager = activityService.getManagerByTicket(ticket);

        if (manager == null) {
            response.sendRedirect("./login.html");
            return true;
        }
        return true;
    }
}
